package com.ly.hotel.spainterface.pp.view;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.ly.hotel.R;
import com.ly.hotel.spainterface.jxd.bean.MachineBean;
import com.ly.hotel.spainterface.pp.bean.PpXFPluginBean;
import com.ly.hotel.spainterface.pp.bean.PreReturnBean;
import com.ly.hotel.spainterface.pp.bean.PreXFDataBean;
import com.ly.hotel.spainterface.pp.event.PpDialogCloseEvent;
import com.ly.hotel.spainterface.pp.utils.CommonHttpUtils;
import com.ly.hotel.spainterface.pp.utils.GsonUtils;
import com.ly.hotel.util.ProcessWaitingUtil;

import java.lang.ref.WeakReference;
import java.net.URLEncoder;

import de.greenrobot.event.EventBus;

/**
 * Created by mo on 2018/6/8.
 */

public class PpXFOrderDialog extends Dialog {

    private Context context;
    private final String TAG = "PpXFOrderDialog";
    private final int CONSUME_ORDER_CALL = 0;
    private final int CONSUME_ORDER = 1;
    private ImageButton dialogClose;
    private PreXFDataBean preXFDataBean;
    private PpXFPluginBean ppXFPluginBean;
    private MachineBean machineBean;
    private int consumeItemNum;
    private String actionName;
    private TextView consumeName;
    private TextView consumeNum;
    private TextView consumeTotal;
    private Button confirmOrder;
    private TextView consumeAction;
    private MyHandler handler = new MyHandler(this);

    public PpXFOrderDialog(Context context, int themeResId) {
        super(context, themeResId);
        this.context = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pp_xf_order_dialog);
        initView();
        setDialogClose();
        setData();
        setConsumeOrder();
    }

    private void initView() {
        dialogClose = findViewById(R.id.dialog_close);
        consumeName = findViewById(R.id.consume_name);
        consumeNum = findViewById(R.id.consume_num);
        consumeAction = findViewById(R.id.consume_action);
        consumeTotal = findViewById(R.id.consume_total);
        confirmOrder = findViewById(R.id.confirm_order);
    }

    private void setDialogClose() {
        dialogClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
    }

    private void setData() {
        consumeName.setText(preXFDataBean.getName());
        consumeNum.setText(consumeItemNum + preXFDataBean.getMeasure());

        double totalPrice = 0;
        try {
            totalPrice = Double.parseDouble(preXFDataBean.getPrice()) * consumeItemNum;
        } catch (Exception e) {
            e.printStackTrace();
        }
        consumeTotal.setText(totalPrice + "元");

        if (TextUtils.isEmpty(actionName)) {
            consumeAction.setText("该商品无做法可选");
        } else {
            consumeAction.setText(actionName);
        }
    }

    private void setConsumeOrder() {
        confirmOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (TextUtils.isEmpty(ppXFPluginBean.getPrintPort())) {
                        //打印模式：显示屏
                        getDisplay();
                    } else {
                        /*if (ppXFPluginBean.isDisplayPrint() == true) {
                            //打印模式：打印机+显示屏
                            getDisplay();
                            getPrint();
                        } else {
                            //打印模式：打印机
                            getPrint();
                        }*/
                        getPrint();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ProcessWaitingUtil.showProcessDialog(context, context.getResources().getString(R.string.loading_tips), 10000);

            }
        });
    }

    //显示屏
    private void getDisplay() {
        try {
            String URL = "http://" + ppXFPluginBean.getIp() + ":" + ppXFPluginBean.getPort() + "/api/call.json";
            String request = "";
            if (TextUtils.isEmpty(actionName)) {
                request = "mac=" + machineBean.getMac() + "&content=" + URLEncoder.encode("点单:" +
                        machineBean.getCategoryName() + "-" + machineBean.getTvName() + "," +
                        preXFDataBean.getName() + consumeItemNum + preXFDataBean.getMeasure(), "utf-8") +
                        "&status=0";
            } else {
                request = "mac=" + machineBean.getMac() + "&content=" + URLEncoder.encode("点单:" +
                        machineBean.getCategoryName() + "-" + machineBean.getTvName() + "," +
                        preXFDataBean.getName() + consumeItemNum + preXFDataBean.getMeasure() + "," +
                        actionName, "utf-8") + "&status=0";
            }
            Log.i(TAG, "request=" + request);
            CommonHttpUtils.getResource(URL, request, handler, CONSUME_ORDER_CALL);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //打印机
    private void getPrint() {
        try {
            String URL = "http://" + ppXFPluginBean.getIp() + ":" + ppXFPluginBean.getPrintPort() + "/call.json";
            String request = "";
            if (TextUtils.isEmpty(actionName)) {
                request = "fun=on&content=" + URLEncoder.encode("点单:" + machineBean.getCategoryName() +
                        "-" + machineBean.getTvName() + "," + preXFDataBean.getName() + consumeItemNum +
                        preXFDataBean.getMeasure(), "utf-8");
            } else {
                request = "fun=on&content=" + URLEncoder.encode("点单:" + machineBean.getCategoryName() +
                        "-" + machineBean.getTvName() + "," + preXFDataBean.getName() + consumeItemNum +
                        preXFDataBean.getMeasure() + "," + actionName, "utf-8");
            }
            Log.i(TAG, "request=" + request);
            CommonHttpUtils.getResource(URL, request, handler, CONSUME_ORDER);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("HandlerLeak")
    private class MyHandler extends Handler {
        private WeakReference<PpXFOrderDialog> wrDialog;

        public MyHandler(PpXFOrderDialog ppXFOrderDialog) {
            wrDialog = new WeakReference<PpXFOrderDialog>(ppXFOrderDialog);
        }

        @Override
        public void handleMessage(Message msg) {
            PpXFOrderDialog mDialog = wrDialog.get();
            if (mDialog != null) {
                switch (msg.what) {
                    case 1:
                        ProcessWaitingUtil.closeProcessDialog();
                        String resultString = msg.obj.toString();
                        if (resultString.equals("OK")) {
                            CommentCustomToast.makeText(context, "下单成功，请稍候！", Toast.LENGTH_LONG, true).show();
                        } else {
                            PreReturnBean preReturnBean = GsonUtils.parseSimpleJson(resultString, PreReturnBean.class);
                            if (preReturnBean != null) {
                                if (preReturnBean.getCode() == 200) {
                                    CommentCustomToast.makeText(context, "下单成功，请稍候！", Toast.LENGTH_LONG, true).show();
                                } else {
                                    CommentCustomToast.makeText(context, "下单失败，请联系服务员下单！",
                                            Toast.LENGTH_LONG, false).show();
                                }
                            } else {
                                CommentCustomToast.makeText(context, "下单失败，请联系服务员下单！",
                                        Toast.LENGTH_LONG, false).show();
                            }
                        }
                        dismiss();
                        EventBus.getDefault().post(new PpDialogCloseEvent());
                        break;

                    case 2:
                        ProcessWaitingUtil.closeProcessDialog();
                        CommentCustomToast.makeText(context, "下单失败，请联系服务员下单！",
                                Toast.LENGTH_LONG, false).show();
                        dismiss();
                        EventBus.getDefault().post(new PpDialogCloseEvent());
                        break;
                }
            }
        }
    }

    ;


    public void setPreXFDataBean(PreXFDataBean preXFDataBean) {
        this.preXFDataBean = preXFDataBean;
    }

    public void setPpXFPluginBean(PpXFPluginBean ppXFPluginBean) {
        this.ppXFPluginBean = ppXFPluginBean;
    }

    public void setConsumeItemNum(int consumeItemNum) {
        this.consumeItemNum = consumeItemNum;
    }

    public void setActionName(String actionName) {
        this.actionName = actionName;
    }

    public void setMachineBean(MachineBean machineBean) {
        this.machineBean = machineBean;
    }
}
